/** 
  *@CopyRight(c)2009 company Co.Ltd. 
  *@All right reserved.
  *@module name: App.Base.SystemManage.SystemUserTypeManage
  *@description:
  *
  *@author: lugj
  *@version: 1.0
  *@date: 2009/07/16
  *@last date: 2009/07/18
  *@history:
    1.
    2.
  *@bugs:
    1. 
    2. 
  *
*/ 

Ext.namespace("App.Base.SystemManage");

//SystemUserTypeManage Class
App.Base.SystemManage.SystemUserTypeManage = function(config){
	this.config = config;
	this.MODULE_ID = App.Base.Common.func.generateGlobalUniqueId(this.config, 'SYSUSERTYPEMGR');

	this.opCmd = App.Base.common.param.OP_CMD_NONE;
	this.queryCmd = App.Base.common.param.OP_CMD_QUERY;

	this.waitOpLoadMask = new Ext.LoadMask(Ext.getBody(), {msg: "系统正在处理客户端请求，请稍候...", removeMask: false});
	//this.waitOpLoadMask.show();

	//
	this.handlerReqSuccess = function(response){
		this.waitOpLoadMask.hide();
		//var result = decodeURIComponent(response.responseText);
		var result = Ext.decode(response.responseText);
		//{returnCode: , msg: );
		
		App.Base.Common.func.MESSAGEBOX_SHOW({
			title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
			//msg: result.returnCode + '：'+ result.msg,
			msg: result.msg,
			icon: (result.returnCode == App.Base.common.param.REQ_SUCCESS) ? Ext.MessageBox.INFO:Ext.MessageBox.ERROR
		});
		
		if (result.returnCode == App.Base.common.param.REQ_SUCCESS)
		{
			this.doLoad();
		}
		//
		this.opCmd = App.Base.common.param.OP_CMD_NONE;
	};

	this.handlerReqFailure = function(){
		this.waitOpLoadMask.hide();
		App.Base.Common.func.MESSAGEBOX_SHOW({
			title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
			msg: '服务器请求操作失败，请稍候重试',
			icon: Ext.MessageBox.ERROR
		});	
	};

	this.doRequest = function(config){
		if (config.params != null)
		{
			this.waitOpLoadMask.show();
			
			App.Base.Common.func.request({
				method: 'POST',
				url: App.Base.common.param.SYSUSERTYPEMGR_OPERATION_DATAURL,
				success: this.handlerReqSuccess,
				failure: this.handlerReqFailure,
				scope: this,
				params: config.params
			});
		}	
	};

	this.doLoad = function(){
		this.store.load({params:{start:0, limit: Ext.getCmp('pgtbl' + this.MODULE_ID).pageSize}});
		this.asyncTreeNode.reload();	
	};

	this.handler = function(o){
		if (o.action == App.Base.common.param.BUTTON_ACTION_NONE)
		{
			return;
		}

		var userTypeId = '';
		var userTypeParentId = o.userTypeParentId;
		var userTypeName = Ext.getCmp('userTypeName' + o.MODULE_ID).getValue();
		var userTypeDesc = Ext.getCmp('userTypeDesc' + o.MODULE_ID).getValue();
		var normalImgUrl = Ext.getCmp('normalImgUrl' + o.MODULE_ID).getValue();
		var expandImgUrl = Ext.getCmp('expandImgUrl' + o.MODULE_ID).getValue();
		var displayRankingIndex = Ext.getCmp('displayRankingIndex' + o.MODULE_ID).getValue();
		var sysHoldFlag = Ext.getCmp('sysHoldFlag' + o.MODULE_ID).getValue();
		var state = Ext.getCmp('state' + o.MODULE_ID).getValue();

		if (this.opCmd == App.Base.common.param.OP_CMD_MODIFY)
		{
			userTypeId = o.config.initValues.id;

			if (userTypeId == userTypeParentId)
			{
				App.Base.Common.func.MESSAGEBOX_SHOW({
					title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
					msg: '上级用户类型设置错误',
					icon: Ext.MessageBox.ERROR
				});		
				this.opCmd = App.Base.common.param.OP_CMD_NONE;
				return;
			}
		}

		var params = 'SYS_OP_CMD=' + encodeURIComponent(this.opCmd) 
			+ '&USER_TYPE_ID=' + encodeURIComponent(userTypeId)
			+ '&USER_TYPE_PARENT_ID=' + encodeURIComponent(userTypeParentId)
			+ '&USER_TYPE_NAME=' + encodeURIComponent(userTypeName)
			+ '&USER_TYPE_DESC=' + encodeURIComponent(userTypeDesc)
			+ '&NORMAL_IMG_URL=' + encodeURIComponent(normalImgUrl)
			+ '&EXPAND_IMG_URL=' + encodeURIComponent(expandImgUrl)
			+ '&DISPLAY_RANKING_INDEX=' + encodeURIComponent(displayRankingIndex)
			+ '&SYS_HOLD_FLAG=' + encodeURIComponent(sysHoldFlag)
			+ '&STATE=' + encodeURIComponent(state);
		this.doRequest({params: params});
	};

	this.doAdd = function(){
		this.opCmd = App.Base.common.param.OP_CMD_ADD;
		new App.Base.SystemManage.SystemUserTypeMgrWindow({
			id: this.MODULE_ID,
			title: '新增用户类型',
			iconCls: 'x-menu-personinfolist-add',
			opCmd: this.opCmd,
			initValues: {
				id: App.Base.common.param.SYSUSERTYPEMGR_TREE_ROOTNODE_ID,
				text: App.Base.common.param.SYSUSERTYPEMGR_TREE_ROOTNODE_NORMAL_TITLE
			},
			handler: this.handler,
			scope: this
		}).getMainPanel().show();
	};

	this.doModify = function(){
		if(!this.grid.selModel.hasSelection()) 
		{
			App.Base.Common.func.MESSAGEBOX_SHOW({
				title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
				msg: '请选择修改的用户类型',
				icon: Ext.MessageBox.ERROR
			});					
			return;
		}

		var records = this.grid.getSelectionModel().getSelections();

		this.opCmd = App.Base.common.param.OP_CMD_MODIFY;
		new App.Base.SystemManage.SystemUserTypeMgrWindow({
			id: this.MODULE_ID,
			title: '修改用户类型',
			iconCls: 'x-menu-systemmenusmanage-modify',
			opCmd: this.opCmd,
			initValues: {
				id: records[0].get("userTypeId"),
				text: records[0].get("userTypeName"),
				parentId: records[0].get("userTypeParentId"),
				parentText: records[0].get("userTypeParentName"),
				desc: records[0].get("userTypeDesc"),
				icon: records[0].get("normalImgUrl"),
				expandIcon: records[0].get("expandImgUrl"),
				displayRankingIndex: records[0].get("displayRankingIndex"),
				sysHoldFlag: records[0].get("sysHoldFlag"),
				state: records[0].get("state")
			},
			handler: this.handler,
			scope: this
		}).getMainPanel().show();
	};

	this.doDelete = function(){
		if(!this.grid.selModel.hasSelection()) 
		{
			App.Base.Common.func.MESSAGEBOX_SHOW({
				title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
				msg: '请选择删除的用户类型',
				icon: Ext.MessageBox.ERROR
			});					
			return;
		}

		var userTypeIds = "";
		var records = this.grid.getSelectionModel().getSelections();
		var length = records.length;
		for (var count = 0; count < length; count++)
		{
			userTypeIds += records[count].get("userTypeId");
			if (count < length - 1)
			{
				userTypeIds += App.Base.common.param.SPLIT_CHARS_VERTICAL_LINE;
			}
		}

		Ext.MessageBox.show({
			title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
			msg: '确定要删除选定的用户类型',
			buttons: Ext.MessageBox.YESNO,
			icon: Ext.MessageBox.QUESTION,
			fn: function(btn){
				if (btn == 'yes')
				{
					this.opCmd = App.Base.common.param.OP_CMD_DELETE;
					var params = 'SYS_OP_CMD=' + encodeURIComponent(this.opCmd) 
						+ '&USER_TYPE_ID=' + encodeURIComponent(userTypeIds);
					this.doRequest({params: params});
				}
			},
			scope: this
		});		
	};

	this.doQuery = function(){
		this.queryCmd = App.Base.common.param.OP_CMD_QUERY;
		this.store.load({params:{start:0, limit: Ext.getCmp('pgtbl' + this.MODULE_ID).pageSize}});
	};

	this.doReset = function(){
		Ext.getCmp('wantedUserTypeName' + this.MODULE_ID).setValue('');
	};

	//
	this.asyncTreeNode = new Ext.tree.AsyncTreeNode({
		id: App.Base.common.param.SYSUSERTYPEMGR_TREE_ROOTNODE_ID + this.MODULE_ID,
		text: App.Base.common.param.SYSUSERTYPEMGR_TREE_ROOTNODE_NORMAL_TITLE,
		singleClickExpand: true,
		icon: App.Base.common.param.SYSUSERTYPEMGR_TREE_ROOTNODE_NORMALICON_URL,
		expandIcon: App.Base.common.param.SYSUSERTYPEMGR_TREE_ROOTNODE_EXPANDICON_URL,
		qtip: App.Base.common.param.SYSUSERTYPEMGR_TREE_ROOTNODE_QTIP
	});

	this.tree = new Ext.tree.TreePanel({
		id: 'tree' + this.MODULE_ID,
		border: false,
		autoScroll: true,
		root: this.asyncTreeNode,
		loader: new Ext.tree.TreeLoader({
			dataUrl: App.Base.common.param.SYSUSERTYPEMGR_ASYNC_TREELOADER_DATAURL,
			baseParams: {
				module: encodeURIComponent(this.MODULE_ID)
			},
			listeners: {
				load: function(o, node, response){
				},
				scope: this
			}
		}),
		listeners: {
			beforeexpandnode: function(node){
				node.select();
				node.setIcon(node.attributes['expandIcon']);				
			},
			beforecollapsenode: function(node){
				node.select();
				node.setIcon(node.attributes['icon']);				
			},
			scope: this
		}
	});

    this.store = new Ext.data.Store({
		id: 'store' + this.MODULE_ID,
        proxy: new Ext.data.HttpProxy({url: App.Base.common.param.SYSUSERTYPEMGR_GRID_DATAURL}),
        reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
        }, [
            {name: 'userTypeId'},
            {name: 'userTypeParentId'},
            {name: 'userTypeName'},
            {name: 'userTypeParentName'},
            {name: 'userTypeDesc'},
            {name: 'normalImgUrl'},
            {name: 'expandImgUrl'},
            {name: 'displayRankingIndex'},
            {name: 'sysHoldFlag'},
            {name: 'state'}
        ]),
		listeners: {
			beforeload: function(store, options){
				if ((typeof this.userTypeName)== "undefined")
				{
					this.userTypeName = '%';
				}
				else
				{
					this.userTypeName = Ext.getCmp('wantedUserTypeName' + this.MODULE_ID).getValue();
				}

				options.params.queryCmd = encodeURIComponent(this.queryCmd);
				options.params.userTypeName = encodeURIComponent(this.userTypeName);
			},
			load : function(store, records, options){
			},
			scope: this
		}
    });

	this.sm = new Ext.grid.CheckboxSelectionModel();//{handleMouseDown: Ext.emptyFn}

	this.grid = new Ext.grid.GridPanel({
		id: 'grid' + this.MODULE_ID,
    	border: false,
		autoScroll: true,
        stripeRows: true,
        loadMask: {msg: '系统正在加载用户类型数据，请稍候...'},
        //autoExpandColumn: ,
        enableColumnMove: false,
		sm: this.sm,
        cm: new Ext.grid.ColumnModel([
			new Ext.grid.RowNumberer(),
			{id: 'userTypeId' + this.MODULE_ID, header: '编码', dataIndex: 'userTypeId', hidden: true},
			{header: '上级编码', dataIndex: 'userTypeParentId', hidden: true},
			{header: '名称', dataIndex: 'userTypeName' , width: 168},
			{header: '描述', dataIndex: 'userTypeDesc' , width: 168},
			{header: '上级类型名称', dataIndex: 'userTypeParentName' , width: 168},
			{header: '', dataIndex: 'normalImgUrl' , width: 1, hidden: true},
			{header: '', dataIndex: 'expandImgUrl' , width: 1, hidden: true},
			{header: '', dataIndex: 'displayRankingIndex' , width: 1, hidden: true},
			{header: '系统创建', dataIndex: 'sysHoldFlag' , width: 64, align: 'center', renderer: function(value){
					if (value == '1')
					{
						return "是";
					}
					else if (value == '0')
					{
						return "否";
					}
					else
					{
						return "未知";
					}
			}},
			{header: '状态', dataIndex: 'state', width: 48, align: 'center', renderer: function(value){
					if (value == '0')
					{
						return "<font color='black'>正常</font>";
					}
					else if (value == '1')
					{
						return "<font color='green'>已冻结</font>";
					}
					else
					{
						return "<font color='green'>未知</font>";
					}
			}},
			this.sm
        ]),
        store: this.store,
		tbar: new Ext.Toolbar({
			border: false,
			items : ['-', 
				new Ext.form.TextField({
					id: 'wantedUserTypeName' + this.MODULE_ID,
					emptyText: '请输入搜索的用户类型名称...',
					width: 220,
					enableKeyEvents: true,
					listeners: {
						keydown: function(o, e){
							if (e.getCharCode() == 13)
							{
								this.doQuery();
							}
						},
						scope: this
					}			
			}),
				new Ext.Button({
					id: 'btnQuery' + this.MODULE_ID,
					text: '<font color="#0000E3">搜索</font>',
					iconCls: 'x-button-systemmanage-search',
					handler: function(){
						this.doQuery();
					},
					scope: this
			}), '-',
				new Ext.Button({
					id: 'btnReset' + this.MODULE_ID,
					text: '<font color="#0000E3">重置</font>',
					iconCls: 'x-menu-systemmenusmanage-rset',
					handler: function(){
						this.doReset();
					},
					scope: this
			}), '-', '->', '-', {
					text:'<font color="blue">新增</font>',
					iconCls: 'x-menu-systemmanage-roleadd',
					handler: function(){
						this.doAdd();
					},
					scope: this
				}, '-', {
					text:'<font color="blue">修改</font>',
					iconCls: 'x-menu-systemmanage-rolemodify',
					handler: function(){
						this.doModify();
					},
					scope: this
				}, '-', {
					text:'<font color="blue">删除</font>',
					iconCls: 'x-menu-systemmanage-roledelete',
					handler: function(){
						this.doDelete();
					},
					scope: this
				}, '-']
		}),
		bbar: new Ext.PagingToolbar({
			id: 'pgtbl' + this.MODULE_ID,
            pageSize: App.Base.common.param.GRID_PAGE_SIZE_15,
            store: this.store,
            displayInfo: true,
            displayMsg: '共 {2} 条',//'显示第 {0} 条到 {1} 条记录，共 {2} 条',
            emptyMsg: "没有记录",
            plugins: new Ext.ux.PageSizePlugin()
        }),
        viewConfig: {
            //forceFit: true,
            enableRowBody: true,
            getRowClass: function(record, rowIndex, p, ds) {
                var cls = 'white-row';
                switch (rowIndex%2) {
                    case 1:
                        cls = 'red-row'
                        break;
                }
                return cls;
            }
        },
		listeners: {
			dblclick: function(e){
				this.doModify();
			},
			scope: this
		}
    });

	this.form = new Ext.FormPanel({
		id: 'form' + this.MODULE_ID,
		border: false,
		autoScroll: true,
		tbar: new Ext.Toolbar({
			border: false,
			items : ['-', '->', '-']
		}),
		layout: 'border',
		items: [{
			region: 'west',
			title: '用户类型层级结构',
			width : 220,
			minWidth: 220,
			border: true,
			autoScroll: true,
			split : true,
			collapsible : true,
			layout: 'fit',
			items: [this.tree]
		}, {
			region: 'center',
			title: '用户类型',
			minWidth: 420,
			border: true,
			autoScroll: true,
			layout: 'fit',
			items: [this.grid]
		}]
	});

	this.doLoad();

	//this.form.doLayout();

	//defined methods.
    if((typeof App.Base.SystemManage.SystemUserTypeManage.SIMULATE_SHARED_METHODS_FLAG) == "undefined")
    {
        App.Base.SystemManage.SystemUserTypeManage.SIMULATE_SHARED_METHODS_FLAG = true;   

        App.Base.SystemManage.SystemUserTypeManage.prototype.getMainPanel = function(){   
            return this.form;  
        };
 
        //simulating the class's constructor().
        var __ctor = function(){
        }();
    }
}